import { isObject } from 'lodash';
import { formatDate } from '@const/filter.js';
import {
  queryOrderInfo,
  orderGetAppendInfo,
  distributorProductList,
  invoiceInfoList,
  otherAttachmentList,
  distinguishForOCR,
  editNewspaper
} from '@api/m_mall_web_v1.js';
import ElEditable from '@components/el-editable';
import { IndexService } from './index.service';
import {
  C0LUMNS,
  INVOICE_COLUMNS,
  OTHER_COLUMNS,
  ATTRIBUTE_TYPE_OPTIONS
} from './index.const';
import TableUpload from '~/modules/table-upload';

const indexService = new IndexService();
export default {
  components: {
    ElEditable,
    TableUpload
  },
  data() {
    return {
      delDialogVisible: false,
      erCOdeDialogVisible: false,
      dialogText: '',
      delType: null,
      rowData: {}, // 表格操作栏点击暂存的参数
      currentPage: 1,
      pageSize: 20,
      tableLoading: false,
      loading: false,
      payload: {},
      C0LUMNS,
      INVOICE_COLUMNS,
      OTHER_COLUMNS,
      ATTRIBUTE_TYPE_OPTIONS,
      detailData: {}, // 详情数据
      supplierVo: {},
      addressResDto: {},
      orderAppendPOS: [],
      contractVo: {},
      activeName: 'first',
      otherData: [], // 附件信息列表
      invoiceData: [], // 发票信息列表
      invoiceDataLength: 0, // 暂存获取的发票信息列表的长度，后续提交保存时使用
      otherDataLength: 0, // 暂存获取的附件信息列表的长度，后续提交保存时使用
      extend_model: [], // 传给form-render所需要的经过整理的内容
      extend: {}, // form-render绑定值
      base_extend_data: [], // 附加信息回显参数
      submit_data: {
        // 提交参数
        orderId: this.$route.query.id,
        orderAppendPOS: [], // 附加信息
        orderInvoiceForms: [], // 发票信息
        commonFileForms: [] // 附件信息
      },
      rules: {
        url: [{ required: true, message: '发票电子版', trigger: 'blur' }],
        invoiceCode: [{ required: true, message: '发票代码', trigger: 'blur' }],
        invoiceNum: [{ required: true, message: '发票号', trigger: 'blur' }],
        invoiceTittle: [
          { required: true, message: '发票抬头', trigger: 'blur' }
        ],
        invoiceAmount: [
          { required: true, message: '发票金额', trigger: 'blur' }
        ],
        invoiceDate: [{ required: true, message: '开票日期', trigger: 'blur' }]
      },
      ruleIndex: 0
    };
  },
  async created() {
    this.getDetail();
    this.initNavButtons();
  },
  computed: {
    orderId() {
      return this.$route.query.id;
    }
  },
  methods: {
    // 初始化 导航栏 按钮组
    initNavButtons() {
      const btn = {
        type: 'btn',
        arr: [
          {
            type: 'primary',
            val: '提交保存',
            handle: this.checkRuleForm
          }
        ]
      };
      this.$store.commit('changeLayoutHandle', btn);
    },
    checkRuleForm(val) {
      const invoiceCount = this.invoiceData.length;
      if (invoiceCount <= 0) {
        this.submitEdit();
        return;
      }
      this.ruleIndex = val || 0;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.ruleIndex, invoiceCount);
          if (this.ruleIndex < invoiceCount) {
            this.ruleIndex++;
            if (this.ruleIndex === invoiceCount) {
              this.ruleIndex = 0;
              this.submitEdit();
            } else {
              this.$nextTick(() => {
                this.checkRuleForm(this.ruleIndex);
              });
            }
          } else {
            this.$message.info('请把发票信息填写完整');
            this.ruleIndex = 0;
          }
        } else {
          this.$message.info('请把发票信息填写完整');
          this.ruleIndex = 0;
        }
      });
    },
    // 提交保存编辑的数据
    submitEdit() {
      // 1.附加信息的表单验证
      if (this.orderAppendPOS.length) {
        this.$refs.expandFormRenderer.validate(valid => {
          if (valid) {
            // 根据修改的内容处理成后端需要的数据结构
            const extendResult = this.base_extend_data;
            extendResult.forEach((item, index) => {
              item.attributeValue = this.extend[item.attributeNameValue] || '';
              // 如果表单类型为select,就给根据code赋值对应selectName
              if (item.valueRange) {
                const list = item.valueRange ? JSON.parse(item.valueRange) : [];
                list.forEach(val => {
                  if (val.value === item.attributeValue) {
                    item.selectName = val.label;
                  }
                });
              }
            });
            this.submit_data.orderAppendPOS = extendResult;
            // 2.根据暂存的发票信息列表的原始长度，获取新添加的增量数据
            this.sliceDataList();
          } else {
            this.$message({
              message: '您所填写的附加信息有误，请确认后重新填写填',
              type: 'warning'
            });
          }
        });
      } else {
        this.sliceDataList();
      }
    },
    // 获取增量数据，并做验证
    sliceDataList() {
      this.submit_data.orderInvoiceForms = [];
      this.submit_data.commonFileForms = [];
      const invoiceList = {
        fileName: '',
        fileType: '',
        invoiceAmount: '',
        invoiceCode: '',
        invoiceDate: '',
        invoiceNum: '',
        invoiceTittle: '',
        url: '',
        invoiceSellerName: '', // 开票方
        invoiceCheckCode: '' // 校验码
      };
      const otherList = {
        fileName: '',
        fileType: '',
        fileUrl: ''
      };
      // 2. 根据暂存的发票信息列表的原始长度， 获取新添加的增量数据
      // 发票
      if (this.invoiceData.length !== this.invoiceDataLength) {
        const lengthNum = this.invoiceData.length;
        this.submit_data.orderInvoiceForms = this.invoiceData.slice(
          0,
          this.invoiceData.length - this.invoiceDataLength
        );
        // for (const item in invoiceList) {
        //   if (this.submit_data.orderInvoiceForms[0][item] === '') {
        //     this.$message({
        //       type: 'warning',
        //       message: '发票信息不能为空，请完善后再提交！',
        //       duration: 2000
        //     });
        //     return;
        //   }
        // }
        // if (this.submit_data.orderInvoiceForms[0]['invoiceCode'].length !== 12) {
        //   this.$message({
        //     type: 'warning',
        //     message: '12位发票代码长度错误，请修改后再提交！',
        //     duration: 2000
        //   });
        //   return
        // }
        // if (this.submit_data.orderInvoiceForms[0]['invoiceNum'].length !== 8) {
        //   this.$message({
        //     type: 'warning',
        //     message: '8位发票号长度错误，请修改后再提交！',
        //     duration: 2000
        //   });
        //   return
        // }
        this.submit_data.orderInvoiceForms.map(
          (val, index) => (val.serialNumber = lengthNum - index)
        );
      }
      // 附件
      if (this.otherData.length !== this.otherDataLength) {
        const { length } = this.otherData;
        this.submit_data.commonFileForms = this.otherData.slice(
          0,
          this.otherData.length - this.otherDataLength
        );
        for (const item in otherList) {
          if (this.submit_data.commonFileForms[0][item] === '') {
            this.$message({
              type: 'warning',
              message: '附件信息不能为空，请完善后再提交！',
              duration: 2000
            });
            return;
          }
        }
        this.submit_data.commonFileForms.map(
          (val, index) => (val.serialNumber = length - index)
        );
      }

      // 调用接口提交编辑后的数据
      this.$axios
        .$post(editNewspaper, this.submit_data)
        .then(res => {
          if (res.code === '0') {
            this.$router.go(-1);
            this.$message({
              message: '提交成功',
              type: 'success'
            });
          }
        })
        .catch(err => {
          this.$message({
            type: 'warning',
            message: '提交失败'
          });
        });
    },
    // 发票信息上传回调
    ReturnImgUrlInvoice(url, index, name) {
      this.invoiceData[index].url = url;
      this.invoiceData[index].fileName = name.split('.')[0];
      this.invoiceData[index].fileType = url.replace(/.+\./, '').toLowerCase();
      if (!url) return;
      this.setInvoiceFiledsByFile(url, index);
    },
    // 附件上传回调
    ReturnImgUrlOther(url, index, name) {
      this.otherData[index].fileUrl = url;
      this.otherData[index].fileName = name.split('.')[0];
      this.otherData[index].fileType = url.replace(/.+\./, '').toLowerCase();
    },
    // 根据发票文件获取其他发票信息
    setInvoiceFiledsByFile(url, index) {
      this.loading = true;
      this.$axios({
        method: 'post',
        url: distinguishForOCR,
        data: {
          imgUrl: url
        }
      })
        .then(res => {
          const result = isObject(res.data.payload) ? res.data.payload : {};
          this.invoiceData[index].invoiceCode = result.invoiceCode
            ? result.invoiceCode
            : '';
          this.invoiceData[index].invoiceNum = result.quantity
            ? result.quantity
            : '';
          this.invoiceData[index].invoiceSellerName = result.invoiceSellerName
            ? result.invoiceSellerName
            : '';
          this.invoiceData[index].invoiceCheckCode = result.invoiceCheckCode
            ? result.invoiceCheckCode
            : '';
          this.invoiceData[index].invoiceTittle = result.invoiceTitle
            ? result.invoiceTitle
            : '';
          this.invoiceData[index].invoiceAmount = result.totalAmount
            ? result.totalAmount
            : '';
          this.invoiceData[index].invoiceDate = result.invoiceDate
            ? result.invoiceDate
            : '';
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
          this.loading = false;
        });
    },
    // 删除弹窗
    deleteOne(val, i) {
      i == 1
        ? (this.dialogText = '确定要删除该发票信息吗？')
        : (this.dialogText = '确定要删除该附件吗？');
      this.rowData = val;
      this.delType = i;
      this.delDialogVisible = true;
    },
    // 确定删除
    subDelete() {
      if (this.delType === 1) {
        this.invoiceData.splice(this.rowData.$index, 1);
      } else {
        this.otherData.splice(this.rowData.$index, 1);
      }
      this.delDialogVisible = false;
    },
    // 获取详情
    async getDetail() {
      await this.$axios
        .$post(queryOrderInfo, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.supplierVo = res.payload.supplierVo
              ? res.payload.supplierVo
              : [];
            this.addressResDto = res.payload.addressResDto
              ? res.payload.addressResDto
              : [];
            this.orderAppendPOS = res.payload.orderAppendPOS
              ? res.payload.orderAppendPOS
              : [];
            this.contractVo = res.payload.contractVo
              ? res.payload.contractVo
              : [];
            this.detailData = {
              ...res.payload
            };
            this.detailData.orderAmount =
              this.detailData.orderAmount !== null
                ? this.detailData.orderAmount.toFixed(2)
                : '0.00';
            this.detailData.saleDate = this.detailData.saleDate
              ? formatDate(this.detailData.saleDate, 'YYYY-MM-DD')
              : '';
            if (this.orderAppendPOS.length) {
              const obj = {};
              this.orderAppendPOS.forEach(item => {
                obj[item.attributeNameValue] = item.attributeValue;
              });
              this.extend = obj;
              this.getAppendInfo(res.payload.contractVo);
            }
            this.getDetailList();
            this.getLogistics();
            this.getPayment();
          }
        });
    },
    // 获取附加信息对应的值
    getAppendInfo(obj) {
      this.$axios
        .$post(orderGetAppendInfo, {
          productLineCode: obj.productLineCode,
          vendorNum: obj.supplierCode,
          ddbm: 'WHOLESALE_ISSUE',
          busModel: 4,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.base_extend_data = res.payload;
            this.extend_model = indexService.getFormContent(
              res.payload,
              this.ATTRIBUTE_TYPE_OPTIONS
            );
            // let default_value = {};
            // res.payload.forEach(item => {
            //   default_value[item.attributeNameValue] = item.defaultValue;
            // });
            // this.$nextTick(() => {
            //   this.$refs.expandFormRenderer.updateForm(default_value);
            // });
          }
        });
    },
    addInvoiceItemValidate() {
      const content = this.invoiceData;
      if (content.length < 1) {
        this.addInvoiceData();
      } else {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.addInvoiceData();
          }
        });
      }
    },
    // 添加发票信息
    addInvoiceData() {
      const invoiceList = {
        fileName: '',
        fileType: '',
        invoiceAmount: '',
        invoiceCode: '',
        invoiceDate: '',
        invoiceNum: '',
        invoiceTittle: '',
        invoiceSellerName: '', // 开票方
        invoiceCheckCode: '', // 校验码
        url: ''
      };
      if (this.invoiceData.length > 50) {
        this.$message({
          type: 'warning',
          message: '最多可添加五十条发票信息！',
          duration: 2000
        });
      } else if (this.invoiceData.length === 0) {
        this.invoiceData.unshift(invoiceList);
      } else {
        // for (const item in invoiceList) {
        //   if (this.invoiceData[0][item] === '') {
        //     this.$message({
        //       type: 'warning',
        //       message: '发票信息不能为空，请完善后再添加！',
        //       duration: 2000
        //     });
        //     return;
        //   }
        // }
        // if (this.invoiceData[0]['invoiceCode'].length !== 12) {
        //   this.$message({
        //     type: 'warning',
        //     message: '12位发票代码错误，请修改后再添加！',
        //     duration: 2000
        //   });
        //   return
        // }
        // if (this.invoiceData[0]['invoiceNum'].length !== 8) {
        //   this.$message({
        //     type: 'warning',
        //     message: '8位发票号错误，请修改后再添加！',
        //     duration: 2000
        //   });
        //   return
        // }
        this.invoiceData.unshift(invoiceList);
      }
    },
    addOtherData() {
      const otherList = {
        fileName: '',
        fileType: '',
        fileUrl: ''
      };
      if (this.otherData.length > 50) {
        this.$message({
          type: 'warning',
          message: '最多可添加五十条附件信息！',
          duration: 2000
        });
      } else if (this.otherData.length === 0) {
        this.otherData.unshift(otherList);
      } else {
        for (const item in otherList) {
          if (this.otherData[0][item] === '') {
            this.$message({
              type: 'warning',
              message: '附件信息不能为空，请完善后再添加！',
              duration: 2000
            });
            return;
          }
        }
        this.otherData.unshift(otherList);
      }
    },
    // 获取发票信息
    getPayment() {
      this.$axios
        .$post(invoiceInfoList, {
          newspaperCode: this.detailData.orderCode,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.payload) {
            this.invoiceData = res.payload;
            this.invoiceDataLength = res.payload.length;
          }
        });
    },
    // 获取其他附件
    getLogistics() {
      this.$axios
        .$post(otherAttachmentList, {
          newspaperCode: this.detailData.orderCode,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.payload) {
            this.otherData = res.payload;
            this.otherDataLength = res.payload.length;
          }
        });
    },

    // 获取详情商品列表
    getDetailList() {
      this.tableLoading = true;
      this.$axios
        .$post(distributorProductList, {
          newspaperCode: this.detailData.orderCode,
          page: this.currentPage,
          pageSize: this.pageSize
        })
        .then(res => {
          this.payload = res.payload;
          this.tableLoading = false;
        });
    },
    reloadPagination(val) {
      this.currentPage = val.number;
      this.pageSize = val.size;
      this.getDetailList();
    }
  }
};
